﻿using Core.Web.Api.Swagger;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;
using System;

namespace Core.Web.Api.Utils.Init
{
    /// <summary>
    /// 初始化Swagger 中文
    /// </summary>
    public static class InitSwaggerChinese
    {
        /// <summary>
        /// 使用 Swagger 中文接口文档
        /// </summary>
        /// <param name="services"></param>
        public static void UseSwaggerChinese(this IServiceCollection services)
        {
            if (APIConfig.ApiSetting.UseSwagger)
            {
                //注册Swagger生成器，定义一个和多个Swagger 文档
                services.AddSwaggerGen(c =>
                {
                    c.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo
                    { Title = "TreeHole树洞程序 接口文档", Version = "V1" });


                    // TODO:一定要返回true！
                    c.DocInclusionPredicate((docName, description) =>
                    {
                        return true;
                    });

                    //为 Swagger JSON and UI设置xml文档注释路径
                    var xmlPath = System.IO.Path.Combine(AppContext.BaseDirectory, "Core.Web.Api.xml");
                    //var dbxmlPath = System.IO.Path.Combine(AppContext.BaseDirectory, "Core.DB.xml");
                    //var cxmlPath = System.IO.Path.Combine(AppContext.BaseDirectory, "ARC.Common.xml");
                    c.IncludeXmlComments(xmlPath);
                    //c.IncludeXmlComments(dbxmlPath);
                    //c.IncludeXmlComments(cxmlPath);
                    //添加对控制器的标签(描述)
                    c.DocumentFilter<ApplyTagDescriptions>();
                    c.OperationFilter<SwaggerOperationFilter>();
                    c.DocumentFilter<SwaggerEnumFilter>();

                    #region 启用swagger验证功能
                    //添加一个必须的全局安全信息，和AddSecurityDefinition方法指定的方案名称一致即可，CoreAPI。
                    c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
                    {
                        Description = "JWT授权(数据将在请求头中进行传输) 在下方输入Bearer {token} 即可，注意两者之间有空格",
                        Name = "Authorization",
                        In = ParameterLocation.Header,
                        Type = SecuritySchemeType.ApiKey,

                    });
                    c.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    {
                        new OpenApiSecurityScheme{
                            Reference = new OpenApiReference()
                            {
                            Id = "Bearer",
                            Type = ReferenceType.SecurityScheme,
                            }
                        }
                        , Array.Empty<string>()
                    }
                });
                    #endregion


                }).AddSwaggerGen();

            }
        }
    }
}
